import cv2
from PIL import Image, ImageDraw, ImageFont
import numpy as np
# 打开摄像头
cap = cv2.VideoCapture(1)

def add_text_bar(image, text1, text2, font_path='path/to/font.ttf'):
    # 获取图像尺寸
    height, width = image.shape[:2]
    # 创建一个新的图像，包含原始图像和底部的文本栏
    new_image = cv2.copyMakeBorder(image, 0, 70, 0, 0, cv2.BORDER_CONSTANT, value=(255, 255, 255))

    # 使用PIL绘制中文字符
    pil_image = Image.fromarray(cv2.cvtColor(new_image, cv2.COLOR_BGR2RGB))
    draw = ImageDraw.Draw(pil_image)
    font = ImageFont.truetype(font_path, 20)

    # 将图像从RGB转换回BGR
    return cv2.cvtColor(np.array(pil_image), cv2.COLOR_RGB2BGR)


if not cap.isOpened():
    print("无法打开摄像头")
    exit()

screenshot_counter = 0

while True:
    ret, frame = cap.read()
    if not ret:
        print("无法获取帧")
        break

    # 显示结果
    cv2.imshow('Detection', frame)

    # 按下's'键保存截图
    if cv2.waitKey(10) & 0xFF == ord('s'):
        # Save the current frame with a unique filename
        filename = f'dataimages_{screenshot_counter}.png'  # Create a unique filename
        cv2.imwrite(filename, frame)  # Save the screenshot
        print(f"Screenshot saved as {filename}!")
        screenshot_counter += 1  # Increment the counter

    # 按下'Q'键退出循环
    if cv2.waitKey(10) & 0xFF == ord('q'):
        break

# 释放资源
cap.release()
cv2.destroyAllWindows()
